﻿using Common.Contract;
using Common.Contract.Authentication.Record;
using Common.Contract.Customer;
using Common.Contract.Customer.Record;
using Common.Contract.Customer.Request;
using Common.Contract.Paging;
using Common.Contract.Warranty.Request;
using Common.Contract.Warranty.Response;
using Common.Service;
using Common.Util;
using Common.Service.Command;
using System;
using System.Collections.Generic;
using System.Linq;
using Warranty.Configuration;
using Warranty.Model.Interface;
using Warranty.Model.Model;

namespace Warranty.ServiceCommand
{
    public class SearchSaleOutVerificationServiceCommand : ProviderServiceCommand<IProviderFactory, SearchSaleOutVerificationRequest, SearchSaleOutVerificationResponse>
    {

        public SearchSaleOutVerificationServiceCommand(IProviderFactory provider) : base(provider) { }

        protected override void Validate(SearchSaleOutVerificationRequest request)
        {
            if (request == null) throw new ArgumentNullException("request");
            if (!request.Header.ApplicationKey.HasValue || request.Header.ApplicationKey == Guid.Empty)
            {
                throw new ArgumentException("ApplicationKey must be set", "request");
            }
        }

        protected override bool OnExecute(SearchSaleOutVerificationResponse response)
        {
            bool isSuccess = true;
            string errorMessage = string.Empty;
            int pageSize = 0, pageIndex = 0, totalRecord = 0;
            List<SaleOutVerificationRecord> records = new List<SaleOutVerificationRecord>();
            var applicationKey = Request.Header.ApplicationKey;
            if (Request.Page != null)
            {
                pageIndex = Request.Page.PageIndex ?? 0;
                pageSize = Request.Page.PageSize ?? 0;
            }

            Dictionary<string, ShopInfoRecord> dictShops = new Dictionary<string, ShopInfoRecord>();
            string[] shopcodes = null;
            using (ServiceClient<ICustomer> serviceClient = new ServiceClient<ICustomer>())
            {
                SearchShopInfosRequest requestShops = new SearchShopInfosRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = Request.Header.ApplicationKey,
                        CallerName = "Warranty.ServiceCommand.SearchSaleOutVerificationServiceCommand"
                    },
                    RegId = Request.RegionIdentifier,
                    BillToCode = Request.BillTo,
                    IncludeArea = true
                };

                var responseShops = serviceClient.Proxy.SearchShopInfo(requestShops);
                if (responseShops.IsSuccess)
                {
                    dictShops = responseShops.Records.ToDictionary(x => x.ShopCode);

                    if (!Request.RegionIdentifier.IsNullOrWhiteSpace() && Request.RegionIdentifier != SystemConfiguration.ALL_REGION_CODE)
                    {
                        shopcodes = dictShops.Keys.Select(x => x).ToArray();
                    }
                }
            }


            List<Dealer> dealers = null;
            dealers = Providers.Dealers.SearchDealer(out totalRecord, Request.TextSearch, shopcodes, Request.VerifyFlag, Request.ConfirmFlag, Request.StartDate, Request.EndDate, pageIndex, pageSize);

            if (dealers != null)
            {
                records = dealers.Select((x) =>
                {
                    ShopInfoRecord shopinfo = null;
                    if (dictShops.ContainsKey(x.ShopCode))
                    {
                        shopinfo = dictShops[x.ShopCode];
                    }
                    return new SaleOutVerificationRecord
                    {
                        ConfirmComment = x.CfmComment,
                        ConfirmFlag = x.ConfirmFlag,
                        ConfirmUser = x.CfmUser,
                        EdiNumber = x.EdiNo,
                        Model = x.Model,
                        //Region = x.FullName,
                        SaleInDate = x.SellinDate,
                        SaleOutDate = x.SelloutDate,
                        SeriaNumber = x.SerialNo,
                        ShopInfo = shopinfo,
                        Suffix = x.Suffix,
                        UserCell = x.EuCell,
                        UserVerify = x.UploadUser,
                        VerifyFlag = x.VerifyFlag
                    };
                })/*.Where(x => x.ShopInfo != null)*/.ToList();
            }

            response.Records = records;
            response.Page = new PageRecord
            {
                PageIndex = pageIndex,
                PageSize = pageSize,
                TotalRecords = totalRecord
            };
            return isSuccess;
        }
    }
}
